const u = navigator.userAgent
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

const JSBRIDGE = {
    // 调用
    call: function (methodName, data, callBack, keepBack) {
        var para = {
            'nativeMethodName': methodName
        }
        if (callBack) {
            var callBackName = this.callBackId()
            para.functionName = callBackName

            // 设置回调
            window[callBackName] = function (res) {
                callBack.call(this, JSON.parse(res))

                if (!keepBack) {
                    delete window[callBackName]
                }
            }
        }
        if (data) {
            Object.assign(para, data)
        }

        const jsonStr = JSON.stringify(para)

        // 调用
        if (isAndroid) {
            window.prompt(jsonStr)
        } else if (isiOS) {
            location.hash = encodeURIComponent(jsonStr)
            // 清除hash 历史
            // history.go(-1)
        } else {
            // pc
        }
    },

    callBackId: function () {
        return 'callBack_' + (+new Date() * Math.random()).toFixed()
    }
}

export default JSBRIDGE
